﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;

namespace Money
{
    public partial class ImportNameTidy : Form
    {
        List<DescriptionMatch> _nameList = new List<DescriptionMatch>();
        public List<DescriptionMatch> NameList
        {
            get { return _nameList; }
        }

        bool _newNameList;
        public bool NewNameList
        {
            get { return _newNameList; }
        }

        public ImportNameTidy()
        {
            _newNameList = false;
            InitializeComponent();
        }
        private void LoadCatsFromFileClick(object sender, EventArgs e)
        {
            openCatFile.ShowDialog();

            string filename = openCatFile.FileName;

            // now we have a file we need to determine what type of file it is and then import as required
            _nameList = ImportCSV(filename);

            if (_nameList.Count >= 0)
            {
                bAccept.Enabled = true;
            }

            dgNameTidyList.DataSource = _nameList;
        }

        private List<DescriptionMatch> ImportCSV(string fileName)
        {
            List<DescriptionMatch> nameList = new List<DescriptionMatch>();

            StreamReader sr = new StreamReader(fileName);

            string line;
            Match match;

            while ((line = sr.ReadLine()) != null)
            {
                match = Regex.Match(line, @"^(?<RegularExpression>.*),(?<NewDescription>.*)");

                if (match.Groups.Count >= 2)
                {
                    DescriptionMatch name = new DescriptionMatch();

                    name.Description = match.Groups["NewDescription"].Value;
                    name.RegularExpression = match.Groups["RegularExpression"].Value;

                    nameList.Add(name);
                    _newNameList = true;
                }
            }

            return nameList;
        }

        private void CancelImportHandler(object sender, EventArgs e)
        {
            _newNameList = false;
            this.Close();
        }

        private void AcceptHandler(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
